import { ref, reactive, onMounted, watch } from 'vue';
import { page, search, remove } from '@/chaos/functions/common/Data';

export default function useTableData(domain, searchMethod) {
    const tableData = ref([]);
    const currentPage = ref(1);
    const limit = ref(20);
    const total = ref(0);
    const data = reactive({});
    const loading = ref(false);

    const search = async () => {
        if (!domain) return;
        loading.value = true;
        let res;
        if (searchMethod) {
            res = await search(
                `${domain}/${searchMethod}`,
                currentPage.value,
                limit.value,
                data
            );
        } else {
            res = await page(domain, currentPage.value, limit.value, data);
        }
        const { list, total: totalData } = res;
        tableData.value = list;
        total.value = totalData;
        loading.value = false;
    };
    onMounted(search);
    watch(currentPage, search);
    watch(limit, search);
    watch(data, search);

    const handleCurrentChange = value => {
        currentPage.value = value;
    };
    const handleSizeChange = value => {
        currentPage.value = 1;
        limit.value = value;
    };
    const doDelete = mu => {
        remove(domain, mu, () => search());
    };
    return {
        currentPage,
        limit,
        total,
        tableData,
        data,
        loading,
        doDelete,
        handleCurrentChange,
        handleSizeChange,
        search
    };
}
